#!/bin/bash

set -e

if [ -z "$DEPENDABOT_NATIVE_HELPERS_PATH" ]; then
  echo "Unable to build, DEPENDABOT_NATIVE_HELPERS_PATH is not set"
  exit 1
fi

helpers_dir=$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd)

if [ ! -f "$helpers_dir/lib/NuGet.Client/NuGet.sln" ]; then
  echo "NuGet.sln not found; please run 'git submodule update --init --recursive' and try again"
  exit 1
fi

install_dir="$DEPENDABOT_NATIVE_HELPERS_PATH/nuget"
mkdir -p "$install_dir"

cp -r \
  "$helpers_dir/lib" \
  "$install_dir"

os="$(uname -s | tr '[:upper:]' '[:lower:]')"
arch=$(dpkg --print-architecture)
if [ "$arch" = "amd64" ]; then
  arch="x64"
fi

echo "building NuGetUpdater tool"
cd "$install_dir/lib/NuGetUpdater/NuGetUpdater.Cli"
dotnet publish \
    --configuration Release \
    --output "$install_dir/NuGetUpdater" \
    --framework net9.0 \
    --runtime "$os-$arch"
dotnet clean

echo "verifying NuGetUpdater tool"
"$install_dir/NuGetUpdater/NuGetUpdater.Cli" --version

if [ ! -f "$HOME/.nuget/NuGet/NuGet.Config" ]; then
  echo "user-level NuGet.Config not found; credential patching will not work"
  exit 1
fi
